// Adapted from google's sample code about the notes database

package org.metawatch.manager;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class _4911MEADbAdapter {
	
	/**
	 * MEA database sql columns
	 */
	public static final String KEY_ROWID = "_id";
	public static final String KEY_TIMESTAMP = "timestamp";
	public static final String KEY_TIMER = "timer";
	public static final String KEY_PEDOMETER = "pedometer";
	public static final String KEY_SESSION = "session";

    private static final String TAG = "_4911MEADbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    /**
     * MEA database sql statements
     */

    private static final String DATABASE_NAME = "MEADB";
    private static final int DATABASE_VERSION = 2;
    
    private static final String DATABASE_TABLE_TIMER = "timer";
    private static final String DATABASE_TABLE_PEDOMETER = "pedometer";
    private static final String DATABASE_TABLE_SESSION = "session";
    
    private static final String DATABASE_CREATE_TIMER = "create table timer (_id integer primary key autoincrement, timestamp text not null, timer text not null);";
    private static final String DATABASE_CREATE_PEDOMETER = "create table pedometer (_id integer primary key autoincrement, timestamp text not null, pedometer text not null);";
    private static final String DATABASE_CREATE_SESSION = "create table session (_id integer primary key autoincrement, timestamp text not null, timer text not null, pedometer text not null, session text not null);";
    
    
    private final Context mCtx;

    /**
     * Database connection private class
     * @author MetaWatch-Team32
     *
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

        	db.execSQL(DATABASE_CREATE_TIMER);
        	db.execSQL(DATABASE_CREATE_PEDOMETER);
        	db.execSQL(DATABASE_CREATE_SESSION);
        	
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS timer");
            db.execSQL("DROP TABLE IF EXISTS pedometer");
            db.execSQL("DROP TABLE IF EXISTS session");
            onCreate(db);
        }
    }
    
    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public _4911MEADbAdapter(Context ctx) {
        this.mCtx = ctx;
    }
    
    /**
     * Open the MEA database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public _4911MEADbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    /**
     * Close the database connection
     */
    public void close() {
        mDbHelper.close();
    }
    
    /**
     * Create a timer entry using the time entered. 
     * @param newTime Time to store in the database
     * @return _ID if successful, -1 otherwise
     */
    public long createTimerEntry(String newTime){
    	SimpleDateFormat timeStampFormat = new SimpleDateFormat("MM-dd HH:mm:ss"); 
    	Date date = new Date();
    	ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TIMER, newTime);
        initialValues.put(KEY_TIMESTAMP, timeStampFormat.format(date));
        return mDb.insert(DATABASE_TABLE_TIMER, null, initialValues);
    }
    
    /**
     * Delete all the entries in the timer table
     * @return the number of rows cleared
     */
    public int clearTimerTable(){
    	return mDb.delete(DATABASE_TABLE_TIMER, "1", null);
    }
    
    /**
     * Create a pedometer entry using the pedometer data entered
     * @param newPedometer Pedometer data to store in the database
     * @return _ID if successful, -1 otherwise
     */
    public long createPedometerEntry(String newPedometer){
    	SimpleDateFormat timeStampFormat = new SimpleDateFormat("MM-dd HH:mm:ss"); 
    	Date date = new Date();
    	ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_PEDOMETER, newPedometer);
        initialValues.put(KEY_TIMESTAMP, timeStampFormat.format(date));
        return mDb.insert(DATABASE_TABLE_PEDOMETER, null, initialValues);
    }
    
    /**
     * Delete all the entries in the pedometer table
     * @return the number of rows cleared
     */
    public int clearPedometerTable(){
    	return mDb.delete(DATABASE_TABLE_PEDOMETER, "1", null);
    }
    
    /**
     * Create a session entry using the timer, pedometer, and session data
     * @param sTimer Timer data to store
     * @param sPedometer Pedometer data to store
     * @param session Session number to associate
     * @return _ID if successful, -1 otherwise
     */
    public long createSessionEntry(String sTimer, String sPedometer, String session){
    	SimpleDateFormat timeStampFormat = new SimpleDateFormat("MM-dd HH:mm:ss"); 
    	Date date = new Date();
    	ContentValues initialValues = new ContentValues();
    	initialValues.put(KEY_TIMESTAMP, timeStampFormat.format(date));
    	initialValues.put(KEY_TIMER, sTimer);
    	initialValues.put(KEY_PEDOMETER, sPedometer);
    	initialValues.put(KEY_SESSION, session);
        return mDb.insert(DATABASE_TABLE_SESSION, null, initialValues);
    }
    
    /**
     * Delete all the entries in the session table
     * @return the number of rows cleared
     */
    public int clearSessionTable(){
    	return mDb.delete(DATABASE_TABLE_SESSION, "1", null);
    }
    
    /**
     * Return a Cursor over the list of all entries in the timer table
     * @return Cursor over all timer entries
     */
    public Cursor fetchAllTimers() {
        return mDb.query(DATABASE_TABLE_TIMER, new String[] {KEY_ROWID, KEY_TIMESTAMP, KEY_TIMER}, null, null, null, null, null);
    }
    
    /**
     * Return a Cursor over the list of all entries in the pedometer table
     * @return Cursor over all pedometer entries
     */
    public Cursor fetchAllPedometers() {
        return mDb.query(DATABASE_TABLE_PEDOMETER, new String[] {KEY_ROWID, KEY_TIMESTAMP, KEY_PEDOMETER}, null, null, null, null, null);
    }
    
    /**
     * Return a Cursor over the list of all entries in the session table
     * @return Cursor over all session entries
     */
    public Cursor fetchAllSessions() {
        return mDb.query(DATABASE_TABLE_SESSION, new String[] {KEY_ROWID, KEY_TIMESTAMP, KEY_TIMER, KEY_PEDOMETER, KEY_SESSION}, null, null, null, null, null);
    }
}
